package work.wiwf.web.model.sys.service.impl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import work.wiwf.web.model.sys.bean.vo.SysUserVo;
import work.wiwf.web.model.sys.dao.SysTokenMapper;
import work.wiwf.web.model.sys.service.SysTokenService;

/**
 * @author kehui
 */
@Service
public class SysTokenServiceImpl implements SysTokenService {

	@Resource
	private HttpServletResponse response;
	@Resource
	private HttpServletRequest request;

	@Resource
	private RedisTemplate<String, SysUserVo> redisTemplate;

	@Resource
	SysTokenMapper sysTokenMapper;

	@Override
	public String createToken() {
		String token = UUID.randomUUID().toString();
		return getTagString(token);
	}

	@Override
	public Boolean addTokenUser(String key, SysUserVo val, int timeSeconds) {

		// 写入 redis
		redisTemplate.opsForValue().set(key, val, timeSeconds, TimeUnit.SECONDS);

		// 写入 cookie
		Cookie cookie = new Cookie("ztoken", key);
		cookie.setPath("/");
		response.addCookie(cookie);

		return true;
	}

	@Override
	public Boolean updateTokenUser(String key, SysUserVo val, int timeSeconds) {
		delTokenUser(key);
		addTokenUser(key, val, timeSeconds);
		return true;
	}

	@Override
	public SysUserVo getTokenUser(String key) {
		SysUserVo user = redisTemplate.opsForValue().get(key);

		return user;
	}

	@Override
	public Boolean delTokenUser(String key){
		return redisTemplate.delete(key);
	}

	@Override
	public Boolean updateTokenUserExpire(String key, int timeSeconds) {
		return redisTemplate.expire(key, timeSeconds, TimeUnit.SECONDS);
	}

	@Override
	public String getToken() {
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals("ztoken")) {
				return cookie.getValue().toString();
			}
		}
		return null;
	}

	String getTagString(String tag) {
		try {
			byte md5[] = MessageDigest.getInstance("md5").digest(tag.getBytes());

			return Base64Utils.encodeToString(Base64Utils.encode(md5));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

}
